import yaml

class YamlHandler:
    def __init__(self,file):
        self.file = file

    # 读取yaml数据 使用yaml的load方法将yaml格式转化为字典格式
    def read_yaml(self,encoding='utf-8'):
        '''读取yaml数据'''
        with open(self.file,encoding='utf-8') as f:
            return yaml.load(f.read(), Loader=yaml.FullLoader)

    # 字典格式内容通过yaml的dump方法转化为yaml格式存回config.yaml文件中
    def write_yaml(self, data, encoding='utf-8'):
        """向yaml文件写入数据"""
        with open(self.file, encoding=encoding, mode='w') as f:
            return yaml.dump(data, stream=f, allow_unicode=True)

if __name__ == '__main__':

    # # 读取config.yaml配置文件的数据
    # read_data = YamlHandler('../config/config.yaml').read_yaml()
    # print(read_data)

    data={
        "user":{
            "username":"vivi",
            "password":"123456"
        }
    }
    write_data= YamlHandler('../config/config.yaml').write_yaml(data)

    # 读取config.yaml配置文件的数据
    read_data = YamlHandler('../config/config.yaml').read_yaml()
    print(read_data)
   
